package com.google.code.garbagecan.ejb3study.ws.simple.calculator;

import javax.ejb.Stateless;
import javax.jws.HandlerChain;
import javax.jws.WebService;
import javax.xml.ws.Holder;
import java.util.Date;

@Stateless
@WebService(portName = "CalculatorPort", 
	serviceName = "CalculatorWsService", 
	targetNamespace = "http://superbiz.org/wsdl", 
	endpointInterface = "com.google.code.garbagecan.ejb3study.ws.simple.calculator.CalculatorWs")
@HandlerChain(file = "handler.xml")
public class CalculatorImpl implements CalculatorWs, CalculatorLocal {

	public int sum(int add1, int add2) {
		return add1 + add2;
	}

	public int multiply(int mul1, int mul2) {
		return mul1 * mul2;
	}

	public int factorial(int number, Holder<String> userId,
			Holder<String> returnCode, Holder<Date> datetime) {
		if (number == 0) {
			returnCode.value = "Can not calculate factorial for zero.";
			return -1;
		}

		returnCode.value = userId.value;
		datetime.value = new Date();
		return (int) factorial(number);
	}

	private static long factorial(long n) {
		if (n < 0)
			throw new RuntimeException("Underflow error in factorial");
		else if (n > 20)
			throw new RuntimeException("Overflow error in factorial");
		else if (n == 0)
			return 1;
		else
			return n * factorial(n - 1);
	}
}

